<template>
	<view>
		<view class="" v-if="!isadmin"  style="width: 100vw; justify-content: center;align-items: center;">
			<text>输入密码：</text>
			<input v-model="psw" type="text" placeholder="输入密码"/> 
			<button type="default" size="mini" @click="sure">确定</button>
			
		</view>
		
		<view class="" v-if="isadmin">
			<button @click="test">测试联表查询</button>
		<button @click="textToSpeech">转语音</button>
		<button @click="test2">批量更新数据库</button>
		<button @click="getmsg">取附近的人和信息</button>
		<button @click="getmsglist">获取内存信息记录</button>
		<button @click="setgrids">批量生成格子</button>
		</view>
		
	


		<view class="search" v-if="isadmin">
			<view class="" style="width: 500rpx;height: 80rpx;background-color: beige;margin-top: 20rpx;">	
			<picker mode="selector" :range="pickkeytag" @change="picker">	<text>关键词：{{ keytags }}</text></picker>
			</view>
		
		
			<view class="city"><text>城市：</text><input style="width: 100rpx;" v-model="city" type="text" placeholder="城市名" /></view> 
			<text>共记录：{{ count }}条</text>
			<text>更新：{{upd}}条记录</text>
			<text>增加：{{add}}条记录</text>
			<view class="">
				<button size="mini" @click="search(keytags,city)">搜索周边商业</button>
				<button size="mini" @click="write">写入数据库</button>
			</view>
		
		
		</view>
	</view>
</template>

<script>
import { xunfeiInit } from '../../utils/xunfei.js';
import { keytag } from '../../utils/shopIcon.js';
import { getGridCode } from '../../utils/getSurroundingGrids.js';
const linli = uniCloud.importObject('uni-map-co',{customUI:true});
const xunfei=uniCloud.importObject('linli-obj',{customUI:true})
const app=getApp().globalData
import nicName from'../../utils/madeNicName.js'

export default {
	data() {
		return {
			pickkeytag: this.keytag(),
			keytags: '请选择',
			count: 0,
			isadmin:false,
			poidata: [],
			city:"",
			upd:0,
			add:0,
			location:null,
			psw:""
		};
	},
	onLoad() {
		this.location=getApp().globalData.location
	
	},
	methods: {
		
		sure(){
			if(this.psw==="001"){
				this.isadmin=true
			}else{
				uni.showToast({
					icon:'error',
					title:'密码错误'
				})
			}
		},
		//批量修改用户格子
async setgrids (){
	let count =0
	try{
	const db = uniCloud.databaseForJQL()
  // 获取所有数据
  const res = await db.collection('message_public').limit(6000).get()
  
  // 准备批量更新的数据

  
  for(const msg of res.data){
    // 创建临时location对象
    const location = msg.content.senderLocation
  
     const grid = this.getGridCode(location)
    const r=await db.collection('message_public').where({
		_id:msg._id,
		
	}).update({
		grid:grid
	})  
	if(r.updated===1){
		count++
	} 
	 
console.log(count)
  

  }	
  
	}catch(e){
		console.log('生成格子失败',e);
	}
  
},

getGridCode (location){
  // 保留3位小数的网格编码
  const lonPart = (Math.round(location.longitude * 1000) / 1000).toFixed(3);
  const latPart = (Math.round(location.latitude * 1000) / 1000).toFixed(3);
  return `${lonPart}_${latPart}`;
},
		
		
		//批量修改呢称
		// async btn(){
		// 	const db=uniCloud.databaseForJQL()
		// 	let  count =0
		// const res=await	db.collection('linli-user').limit(6000).get()
		//    for(const name of res.data){
		// 	const data=await   db.collection('linli-user').where({
		// 		   _id:name._id
		// 	   }).update({
		// 		   nicName:nicName()
		// 	   })
		// 	   count+=data.updated
		// 	console.log(count)  
		//    }
			
			
		// },
		
		
		
		
		
		keytag,
	async	textToSpeech() {
			const text="我今天有一件衣服要拿去洗，请问有谁知道哪里有干洗店？"
	// const xunfeiUrl=  await	xunfei.xunfei(text)
	// 	    console.log("讯飞",xunfeiUrl)
  const data =await	xunfeiInit(text)
			console.log(data)
			},
		
		picker(e) {
			this.keytags = this.pickkeytag[e.detail.value];
		},
		//测试联合表查询
		async test() {
			try {
				const db = uniCloud.databaseForJQL(); // 假设使用 uniCloud 数据库，需要根据实际情况初始化
				const groups = await db
					.collection('Group')
					.where({ _id: '67ebfe0f20776526c2ee421b' })
					.update({
						groupUser: ['HOIK9661', 'RQUJ4542', 'OEJP3841'] // 直接添加数组
					});
				console.log(groups);
			} catch (error) {
				console.error('添加记录失败:', error);
			}
		},
		//批量增加格子
		async test2() {
			try {
				const msgs = await db.collection('linli-user').limit(1000).get();
				console.log(msgs);
				if (msgs && Array.isArray(msgs.data)) {
					const batchSize = 100;
					for (let i = 0; i < msgs.data.length; i += batchSize) {
						const batch = msgs.data.slice(i, i + batchSize);
						for (const msg of batch) {
							const bb = await db
								.collection('opendb-poi')
								.where({
									userId: msg.userId
								})
								.update({
									userInfo: msg
								});
							console.log(JSON.stringify(bb));
						}
					}
				} else {
					console.error('数据库查询结果格式不正确:', msgs);
				}
			} catch (error) {
				console.error('操作数据库时出错:', error);
			}
		},
		getGridCode(location) {
			const lonPart = (Math.round(location.longitude * 1000) / 1000).toFixed(3);
			const latPart = (Math.round(location.latitude * 1000) / 1000).toFixed(3);
			return `${lonPart}_${latPart}`;
		},
		async getmsg() {
			const u = await linli.getNearbyInfo(getApp().globalData.location, 2, 20);
			console.log(u.onlineUsersdata);
		},
		async getmsglist() {
			uni.setStorageSync('T1743519245732', []);
			// const db=uniCloud.databaseForJQL()
			// await db.collection("Group").where({
			// 	groupId:"T1743519245732"
			// }).update({
			// 	groupUser:[]
			// })
		},
		async search(keyword,city) {
			this.upd=0
			this.count=0
			this.add=0
			if (!keyword||!city||!this.location) {
				uni.showToast({
					title: '定位关键词城市'
				});
				return
			}
				console.log('断点1')
			try {
				const data = {
					types: '',
					sortrule: 'distance',
					offset: 25,
					show_fields: 'business,photos,navi',
					page: 1,
					keyword: keyword,
					location: {
						lat: this.location.latitude ,
						lng: this.location.longitude
					},
					radius: 1000,
					auto_extend: 1,
					get_subpois: 1,
					orderby: 'distance',
					page_index: 1,
					page_size: 100,
					city: city
				};
				console.log('断点2')
				const res = await linli.search(data);
				console.log("取到的店铺信息",res)
				if (res.result.result.data.length > 0) {
					console.log('成功',res)
					this.poidata = res.result.result.data;
					this.count=this.poidata.length
				} else {
					uni.showToast({
						title: '没有数据'
					});
				}
			} catch (e) {
				uni.showToast({
					title: e
				});
			}
		},
		async write() {	
			const db = uniCloud.databaseForJQL();
		
			if (this.poidata.length === 0) {
				uni.showToast({
					title: '没有数据'
				});
				return;
			}
			try {
			
				for (const item of this.poidata) {
					const updata = {
						sendshopId: item.id,
						title: item.title,
						tel: item.tel,
						address: item.address,
						category: this.keytags,
						location: new db.Geo.Point(item.location.lng, item.location.lat),
						distance: item.distance,
						adcode: item.adcode,
						province: item.province,
						city: item.city,
						district: item.district,
						navi: item.navi,
						photos: item.photos,
						children: item.children,
						business: item.business,
						sendTime: new Date().getTime(),
						sendUserId: item.sendUserId
					};

				
					const isdata = await db
						.collection('sendshop')
						.where({
							sendshopId: item.id
						})
						.get();
					if (isdata.data.length > 0) {
					const upd=	await db
							.collection('sendshop')
							.where({
								sendshopId: item.id
							})
							.update(updata);
							console.log('更新信息',upd)
					if(upd.updated===1){this.upd++}
					} else {
					 const add= await db.collection('sendshop').add(updata);
					 if(add.id){this.add++}
					}
				}
			} catch (addOrUpdateErr) {
				console.error(`处理数据 ${item.id} 时出错：`, addOrUpdateErr);
			}
		},

					
	//为旧群增加网格编码				
	async addgrid() {
	  const db = uniCloud.databaseForJQL()
	  
	  try {
	    // 获取所有分组数据
	    const { data: groups } = await db.collection('Group').get()
	    
	    // 遍历每个分组
	    for (const group of groups) {
	      // 从分组数据中提取经纬度
	      const longitude = group.location.coordinates[0]
	      const latitude = group.location.coordinates[1]
	      
	      // 计算网格编码
	      const grid = getGridCode({ longitude, latitude })
	      
	      // 更新当前分组的网格编码
	      await db.collection("Group")
	        .where({ _id: group._id }) // 正确的where条件写法
	        .update({ grid })
	      
	      console.log(`成功更新分组 ${group._id} 的网格编码为 ${grid}`)
	    }
	    
	    console.log('所有分组网格编码更新完成')
	  } catch (error) {
	    console.error('更新网格编码时出错:', error)
	  }
	}
     
	}
	
	
};
</script>

<style>
.search {
	width: 750rpx;
	height: 300rpx;
	padding-bottom: 50rpx;
	background-color: #ccc;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	margin: 30rpx;
}
.city{
	display: flex;
	flex-direction: row;
	margin-top: 50rpx;
	margin-bottom: 50rpx;
	width: 300rpx;
	
}
</style>